<template></template>
<script setup lang="ts">
import { fireInsuranceStore } from '@/pages/forestry/store/store'
import * as L from 'leaflet'
import yulinSideGeojson from '@/assets/data/yulin-side.json'
import taiyuanQxGeojson from '@/assets/data/taiyuan-qx.json'
const fireStore = fireInsuranceStore()
const baseMap = inject('baseMap')
let clickLatlng = inject('clickLatlng')
let rightPosition = inject('rightPosition')
let countyName = ref()
useEventBus('update:rightWgyb').on(() => {
  if (rightPosition) toRaw(baseMap.value).removeLayer(rightPosition)
})
const handleMapClick = ev => {
  if (isPointWithinYulinRegion(ev.latlng)) {
    clickLatlng.value.lat = ev.latlng.lat
    clickLatlng.value.lng = ev.latlng.lng

    fireStore.lqAllDataList.geometries.forEach((geometries, index) => {
      let coordinates = geometries.coordinates[0]
      if (geometries.type == 'Polygon') {
        // 待查询的点
        const point = {
          type: 'Point',
          coordinates: [ev.latlng.lng, ev.latlng.lat]
        }
        if (isPointInPolygon(point, coordinates)) {
          useEventBus('handleBureauDialogVisible').emit(
            true,
            geometries.bureauDetail
          )
        }
      }
    })
  } else {
    console.log(ev.latlng, '点不在山西区域内')
  }
}

baseMap.value.on('click', handleMapClick)
const yulinRegion = L.geoJSON(yulinSideGeojson)
let isPointWithinYulinRegion = point => {
  let polygonLayer = yulinRegion._layers[Object.keys(yulinRegion._layers)[0]]
  let polygonBounds = polygonLayer.getBounds()
  // 判断点是否在多边形的边界范围内
  if (polygonBounds.contains(point)) {
    return true
  }
  return false
}
// 判断点是否在多边形内部的函数
function isPointInPolygon(point, polygon) {
  let isInside = false
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const xi = polygon[i][0]
    const yi = polygon[i][1]
    const xj = polygon[j][0]
    const yj = polygon[j][1]
    const intersect =
      yi > point.coordinates[1] !== yj > point.coordinates[1] &&
      point.coordinates[0] <
        ((xj - xi) * (point.coordinates[1] - yi)) / (yj - yi) + xi
    if (intersect) isInside = !isInside
  }

  return isInside
}
onMounted(() => {})

onUnmounted(() => {
  baseMap.value.off('click', handleMapClick)
})
</script>
<style lang="scss" scoped></style>
